package com.icss.company.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadController {

    @PostMapping("/upload")
    public Map<String,Object> upload(@RequestParam("cover") MultipartFile multipartFile,String desc, HttpServletRequest request) throws IOException {

        System.out.println("desc ============= " + desc);
        Map<String,Object> result = new HashMap<>();
        String path = request.getServletContext().getRealPath("upload");
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }

        String oldName = multipartFile.getOriginalFilename();
        String ext = oldName.substring(oldName.lastIndexOf("."));
        String newName = System.currentTimeMillis()+ext;
        File newFile = new File(file,newName);
        multipartFile.transferTo(newFile);

        result.put("code",200);
        result.put("msg","success");
        return result;
    }

}
